package service

import (
	"server/internal/model"

	"github.com/jinzhu/gorm"
)

func (svc *Service) Register(username, password string) (bool, error) {

	tx := svc.engine.Begin()

	a := &model.Account{
		Username: username,
		Password: password,
		Rank:     model.StudentRank,
	}
	_, err := a.GetByUsername(svc.engine)
	if err == nil {
		tx.Rollback()
		return false, nil
	}
	if err != nil && err != gorm.ErrRecordNotFound {
		tx.Rollback()
		return false, err
	}

	err = a.Create(svc.engine)
	if err != nil {
		tx.Rollback()
		return false, err
	}

	tx.Commit()
	return true, nil
}

func (svc *Service) Login(username, password string) (int, error) {
	a := &model.Account{
		Username: username,
		Password: password,
	}
	account, err := a.Get(svc.engine)

	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return model.NoRank, nil
		}
		return model.NoRank, err
	}

	return account.Rank, nil
}

func (svc *Service) GetAllUsers() ([]*model.Account, error) {
	a := &model.Account{}
	return a.List(svc.engine, 0, 0)
}

func (svc *Service) GetAllStudents() ([]*model.Account, error) {
	a := &model.Account{Rank: model.StudentRank}
	return a.List(svc.engine, 0, 0)
}

func (svc *Service) GetAllTeachers() ([]*model.Account, error) {
	a := &model.Account{Rank: model.TeacherRank}
	return a.List(svc.engine, 0, 0)
}

func (svc *Service) RemoveUser(id int) error {
	a := &model.Account{}
	a.ID = id
	return a.Delete(svc.engine)
}

func (svc *Service) IncreaseRank(id int) error {
	a := &model.Account{}
	a.ID = id
	value := map[string]interface{}{
		"rank": model.TeacherRank,
	}
	return a.Update(svc.engine, value)
}
